import Vue from 'vue'
import VueRouter from 'vue-router'

//全局状态
import state from './state'

//使用 vue-router 插件
Vue.use(VueRouter)

//导入组件
import Home from './components/Home.vue'
import FAQ from './components/FAQ.vue'
import Login from './components/Login.vue'
import TicketsLayout from './components/TicketsLayout.vue'
import Tickets from './components/Tickets.vue'
import NewTicket from './components/NewTicket.vue'
import Ticket from './components/Ticket.vue'
import NotFound from './components/NotFound.vue'

//routes数组, 将作为参数使用
const routes = [
    {
        path: '/', 
        name: 'home', 
        component: Home 
    },
    {
        path: '/faq', 
        name: 'faq', 
        component: FAQ
    },
    {
        path: '/login', 
        name: 'login', 
        component: Login, 
        meta: {guest: true}
    },
    {
        path: '/tickets', 
        name: 'tickets', 
        component: TicketsLayout, 
        meta: {private: true},
        children: [
            { path: '', name: 'tickets', component: Tickets },
            { path: 'new', name: 'new-ticket', component: NewTicket },
            { path: ':id', name: 'ticket', component: Ticket, props: route =>({id: route.params.id}) },
        ],
    },
    {
        path: '*',
        component: NotFound
    }
]

//实例化 VueRouter 并传入 routes参数
const router = new VueRouter({
    routes,
    mode: 'history',
    scrollBehavior (to, from, savedPosition){
        if (savedPosition) {
            return savedPosition
          }
          if (to.hash) {
            return { selector: to.hash }
          }
          return { x: 0, y: 0 }
    }
})

//路由守卫
router.beforeEach((to, from, next) => {
    // 这种方法 存在 子路由时无效
    // if(to.meta.private && !state.user){
    //     console.log(state.user);
    //     next({
    //         name: 'login',
    //         params: {
    //             wantedRoute: to.fullPath,
    //         }
    //     })
    //     return
    // }
    // if (to.meta.guest && state.user) {
    //     console.log('entery')
    //     next({name: 'home'})
    //     return
    // }
    if(to.matched.some(r=>r.meta.private) && !state.user){
        next({
            name: 'login',
            params: {
                wantedRoute: to.fullPath,
            }
        })
        return
    }
    // to.matched  是vue-router 提供的一个方法,得到的是一个数组, some 是es数组的方法
    if (to.matched.some(r=>r.meta.guest) && state.user) {
        console.log('entery')
        next({name: 'home'})
        return
    }
    next()
    
})

//模块导出
export default router
